import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useNotesStore = defineStore(
  'notes',
  () => {
    // 笔记数据
    const notesData = ref<Record<string, any[]>>({})
    // 当前笔记
    const currentNote = ref<any>(null)

    // 获取指定集合的笔记列表
    const getNotesByCollection = computed(() => {
      return (type: string, id: number) => {
        const key = type === 'doll' ? `doll-${id}` : `notebook-${id}`
        return (notesData.value[key] || []).sort((a, b) => {
          return (
            new Date(b.updateTime || b.createTime).getTime() -
            new Date(a.updateTime || a.createTime).getTime()
          )
        })
      }
    })

    // 添加或更新笔记
    const saveNote = (type: string, collectionId: number, note: any) => {
      const key = type === 'doll' ? `doll-${collectionId}` : `notebook-${collectionId}`

      if (!notesData.value[key]) {
        notesData.value[key] = []
      }

      const index = notesData.value[key].findIndex((n) => n.id === note.id)
      if (index > -1) {
        notesData.value[key][index] = note
      } else {
        notesData.value[key].unshift(note)
      }

      // 更新当前笔记
      currentNote.value = note
    }

    // 设置当前笔记
    const setCurrentNote = (note: any) => {
      currentNote.value = note
    }

    // 格式化时间
    const formatTime = (time: string) => {
      const date = new Date(time)
      const now = new Date()
      const diff = now.getTime() - date.getTime()

      if (diff < 60 * 1000) return '刚刚'
      if (diff < 60 * 60 * 1000) return `${Math.floor(diff / (60 * 1000))}分钟前`
      if (diff < 24 * 60 * 60 * 1000) return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
      if (diff < 30 * 24 * 60 * 60 * 1000) return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`

      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(
        date.getDate(),
      ).padStart(2, '0')}`
    }

    return {
      notesData,
      currentNote,
      getNotesByCollection,
      saveNote,
      setCurrentNote,
      formatTime,
    }
  },
  {
    persist: true,
  },
)
